package com.v5.ik;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.support.v4.util.LruCache;
import android.util.DisplayMetrics;

import com.android.volley.toolbox.ImageLoader.ImageCache;

public class LruBitmapCache extends LruCache<String, Bitmap> implements
		ImageCache {
	/** 缓存目录 */
	private String cacheDir;

	public LruBitmapCache(int maxSize) {
		super(maxSize);
	}

	public LruBitmapCache(Context ctx) {
		this(getCacheSize(ctx));
		cacheDir = ctx.getCacheDir().toString() + File.separator;
	}

	@Override
	protected int sizeOf(String key, Bitmap value) {
		return value.getRowBytes() * value.getHeight();
	}

	@Override
	public Bitmap getBitmap(String url) {
		Bitmap bitmap = get(url);
		if (bitmap == null) {
			File file = new File(cacheDir + MD5.md5(url));
			if (file.exists()) {
				bitmap = BitmapFactory.decodeFile(file.toString());
			}
		}

		return bitmap;
	}

	@Override
	public void putBitmap(String url, Bitmap bitmap) {
		put(url, bitmap);
		File file = new File(cacheDir + MD5.md5(url));
		FileOutputStream os = null;
		try {
			os = new FileOutputStream(file, false);
			bitmap.compress(CompressFormat.JPEG, 99, os);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				if (os != null) {
					os.flush();
					os.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	// Returns a cache size equal to approximately three screens worth of
	// images.
	public static int getCacheSize(Context ctx) {
		final DisplayMetrics displayMetrics = ctx.getResources()
				.getDisplayMetrics();
		final int screenWidth = displayMetrics.widthPixels;
		final int screenHeight = displayMetrics.heightPixels;
		// 4 bytes per pixel
		final int screenBytes = screenWidth * screenHeight * 4;

		return screenBytes * 3;
	}
}
